Repository navigation
feat(ios): replay recorded alert surfaces on the host - #4115
Conversation
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
Size Report
Startup median (7 runs, lower is better):
|
There was a problem hiding this comment.
All reported issues were addressed across 19 files
Reply with feedback, questions, or to request a fix.
View guided diff | Turn on auto-fix | Re-trigger cubic
|
I found no code problems at fea511f. The 24 checks are green, and the macOS smoke gate ios-snapshot-differential runs Not blocking, take or leave: (1) The recorded-node format declares a private Of the six open Cubic threads, three still apply and are small tooling fixes: the capture script's stdio hides xcodebuild failure reasons (#4115 (comment)), the For evidence, I did not run |
The rules that decide which node is an alert surface (alert, sheet, Safari dialog, dismiss popup), which window hosts it, and the presentation the runner compares after a tap now live in AgentDeviceSnapshotPresentation as AlertSurface. The runner observes alerts through them. A corpus of whole trees recorded from simulators, each with the surfaces it must yield, replays on the host through swift test. Record a tree with pnpm capture:alert-surface, which runs a runner test method on the device. The first corpus covers SpringBoard and Safari "Open in app" prompts on an iPhone Duo, folded and unfolded, plus a screen with no prompt. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
… per line Address review on the alert surface corpus: the capture shows xcodebuild's output and removes its temporary directory, the loader rejects a node whose parent is missing, frames use the FixtureRect spelling, AlertSurface owns the actionable types, and each recorded node is one line. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
fea511f to
7b89cba
Compare
|
Addressed at 7b89cba (rebased on #4113's new head 2624508).
Validation:
|
Apex SentinelVerdict: 8 finding(s): 2 minor, 6 nit. Verdict: approve. reached max rounds (1). 🟡 Minor (2)
🔵 Nit (6)
Reply under an inline comment with |
There was a problem hiding this comment.
Apex Sentinel: 8 new findings on 7b89cba. The verdict and the full list are in the summary comment.
| .checkBox, | ||
| .switch | ||
| ] | ||
| let actionableTypes: Set<XCUIElement.ElementType> = Set( |
There was a problem hiding this comment.
🟡 Minor · Runner actionableTypes silently drops any shared name its own raw-value table lacks
actionableTypes is rebuilt by looking AlertSurface.actionableTypes names up in RunnerTests.elementTypeNamesByRawValue (RunnerTests+Snapshot.swift:78), a runner-local table. The match is stringly typed and compactMap drops every miss without a signal: add "RadioButton", "Toggle" or "Link"-like names to the shared AlertSurface.actionableTypes in apple/snapshot-presentation/Sources/AgentDeviceSnapshotPresentation/AlertSurface.swift:52, and the runner's set loses that type in silence. Consequence: actionableElements(in:) and firstAlertText stop treating that element as an action, so RunnerAlert.buttons can end up with no button for a real prompt while the corpus's AlertSurface.presentation(of:) still reports it as a button — the two readers of one rule diverge, which is the drift this PR exists to remove. Nothing in the checkout asserts the pair agrees: no test feeds AlertSurface.actionableTypes through elementTypeNamesByRawValue and asserts the result has the same count.
| let actionableTypes: Set<XCUIElement.ElementType> = Set( | |
| let actionableTypes: Set<XCUIElement.ElementType> = Set( | |
| AlertSurface.actionableTypes.compactMap { name in | |
| RunnerTests.elementTypeNamesByRawValue.first { $0.value == name }?.key.map(XCUIElement.ElementType.init(rawValue:)) | |
| }.compactMap { $0 } | |
| ) |
Suggested change
Assert the invariant instead of trusting it: a unit test that every name in AlertSurface.actionableTypes appears in RunnerTests.elementTypeNamesByRawValue.values (and that the derived set has AlertSurface.actionableTypes.count members), so a new shared type either resolves or fails the test.
Details
Also raised here
Also raised at this location by senior-developer: Runner actionableTypes now depends on unenforced string equality between two tables — RunnerTests.actionableTypes used to be a literal Set<XCUIElement.ElementType> of .button, .cell, .link, .menuItem, .checkBox, .switch, which the compiler checked. It is now rebuilt by looking up AlertSurface.actionableTypes (the Swift package's Set<String>: ["Button", "Cell", "Link", "MenuItem", "CheckBox", "Switch"]) inside RunnerTests.elementTypeNamesByRawValue and converting each raw value back with XCUIElement.ElementType(rawValue:). The set is only complete while three unrelated tables agree exactly, case-sensitively: AlertSurface.actionableTypes (apple/snapshot-presentation/Sources/.../AlertSurface.swift:54) XCUIElement.ElementType(rawValue:) accepting those raw values again Nothing enforces that agreement. …
Also raised at this location by swift-ios: actionableTypes now derived through string names, so a name divergence silently drops an element type — RunnerTests.actionableTypes was a literal set of six XCUIElement.ElementType values. It is now rebuilt by matching AlertSurface.actionableTypes (strings) against elementTypeNamesByRawValue and converting the raw value back. The two sides agree only because the strings in AlertSurface.swift:54 ("Button", "Cell", "Link", "MenuItem", "CheckBox", "Switch") all happen to appear in the raw-value table at RunnerTests+Snapshot.swift:78-111, and nothing enforces that. If AlertSurface.actionableTypes gains a name the table lacks (or a table entry is renamed), compactMap yields nil for it and that element type silently disappears from actionableTypes — used by actionableElements(in:) (RunnerTests+SystemModal.swift:168), the modal-button filter at RunnerTests+SystemModal.swift:179 and firstAlertText (RunnerTests+Alert.swift:328). …
Also raised at this location by maintainability: RunnerTests.actionableTypes is now derived from a name table with nothing pinning the six names — RunnerTests.swift:238-242 replaces the literal [.button, .cell, .link, .menuItem, .checkBox, .switch] with a round trip rawValue -> name in RunnerTests.elementTypeNamesByRawValue -> AlertSurface.actionableTypes -> XCUIElement.ElementType(rawValue:). The set is only the old six if that table spells all six exactly Button, Cell, Link, MenuItem, CheckBox, Switch. A name change or a missing raw value in the table drops that type from actionableTypes with no compile error and no failing assertion, and the corpus cannot catch it: alertSurfaceNode builds the type string through the same table, so a missing entry (the Element(N) spellings in the fixtures) is invisible to both sides. Buttons then land in content instead of buttons, so the presentation the runner compares after a tap changes and alert verification misreports.
persona: javascript, senior-developer, swift-ios, maintainability
Reply @apex-sentinel-staging note ... to add context, or @apex-sentinel-staging pivot ... if this is wrong — I will re-check the cited code.
Useful? Reply @apex-sentinel-staging like, or @apex-sentinel-staging dislike <why> if it is not.
| const xctestrun = fs.readdirSync(products).find((file) => file.endsWith('.xctestrun')); | ||
| if (!xctestrun) throw new Error(`No .xctestrun in ${products}`); | ||
|
|
||
| const outputDir = fs.mkdtempSync(path.join(os.tmpdir(), 'alert-surface-')); |
There was a problem hiding this comment.
🟡 Minor · Capture script writes into the host tmpdir and reads it back from a simulator process
testCaptureAlertSurfaceTree runs inside the simulator's test-runner process, and output is a host path from fs.mkdtempSync(path.join(os.tmpdir(), ...)) passed through TEST_RUNNER_AGENT_DEVICE_ALERT_SURFACE_OUTPUT. The script then treats a missing file as if (!fs.existsSync(output)) throw new Error('The capture test wrote no tree'). The simulator rewrites absolute paths into the device's simulated filesystem (its own /tmp, /var), so the JSON the test writes lands in the simulator's tmp, not the host directory the script created — the script's own existence check then fails with a message that blames the test instead of the path. Use a path the host and the simulator both see (the repo checkout, e.g. under .tmp/alert-surface-runner/, or copy the file out with xcrun simctl get_app_container/xcrun simctl spawn ... cat), and make the failure name both paths.
Suggested change
Verify the capture on a machine other than the author's: write the tree to a path both the host process and the booted simulator resolve identically (for example under the repo's .tmp/), or retrieve the file with xcrun simctl spawn <udid> cat <path> instead of fs.readFileSync.
Details
persona: javascript
Reply @apex-sentinel-staging note ... to add context, or @apex-sentinel-staging pivot ... if this is wrong — I will re-check the cited code.
Useful? Reply @apex-sentinel-staging like, or @apex-sentinel-staging dislike <why> if it is not.
| } | ||
| guard Date() < deadline, let snapshot = try? ownerApp.snapshot(), | ||
| !snapshot.children.isEmpty, !snapshot.frame.isNull, !snapshot.frame.isEmpty else { return } | ||
| let root = self.alertSurfaceNode(snapshot) |
There was a problem hiding this comment.
🔵 Nit · observeAlert converts the whole snapshot tree into AlertSurfaceNode structs on every verification poll
observeAlert now builds an AlertSurfaceNode for every node of the owner app's snapshot tree (alertSurfaceNode(snapshot) at RunnerTests+AlertObservation.swift:40) before it applies any rule, and handleAlert re-runs observeAlert in a loop every 0.2 s until the deadline (while true at RunnerTests+Alert.swift:118-131). The predecessor walked XCUIElementSnapshot in place, so the only allocation was the [XCUIElementSnapshot] candidate array, and it stopped recursing once a match was found. Each converted node allocates a struct holding two Swift Strings (identifier, label) plus a children array, so a SpringBoard tree of the size in the corpus (254 nodes, many with long labels) is deep-copied on each poll for the whole alert budget — up to ~50 full-tree copies for the default 10 s defaultAlertCommandTimeout, all on the main actor while the app is still settling. captureAlertPresentation pays the same conversion once per alert accept. Nothing is incorrect today; the cost is new and it lands on the slow path the surrounding comments already care about (a starved host delaying reads). AlertSurface.candidates could take the snapshot tree through a protocol/accessor, or the conversion could stop descending once a candidate is found.
Suggested change
Avoid rebuilding the whole tree as AlertSurfaceNode per observation poll: either give AlertSurface a view over XCUIElementSnapshot, or reuse one conversion across the verification loop when the tree is unchanged.
Details
persona: swift-ios
Reply @apex-sentinel-staging note ... to add context, or @apex-sentinel-staging pivot ... if this is wrong — I will re-check the cited code.
Useful? Reply @apex-sentinel-staging like, or @apex-sentinel-staging dislike <why> if it is not.
| public static let safariDialogIdentifier = "SFDialogView" | ||
|
|
||
| /// A popover's dismiss region: a label or identifier that reads "dismiss popup", in any case, | ||
| /// with any surrounding whitespace. XCTest queries take it as a `MATCHES[c]` pattern. |
There was a problem hiding this comment.
🔵 Nit · isDismissPopupMarker re-anchors the XCTest pattern by string interpolation
AlertSurface.swift:55-57 builds "^\(dismissPopupMarkerPattern)$" so a constant documented as a MATCHES[c] pattern is reused as the body of an un-anchored range(of:) regex. The correctness rests on that pattern being a single un-anchored sequence with no alternation: add one alternative to dismissPopupMarkerPattern and ^a|b$ anchors only the first/last branch and dismiss-popup windows stop (or start) matching in the corpus while the runner's still-unanchored dismissPopupMarker NSPredicate keeps its old meaning. Keep the whole-string matching of the predecessor with anchored: true on both ends, or store the pattern already anchored and let the XCTest predicate take the anchored form.
Details
persona: maintainability
Reply @apex-sentinel-staging note ... to add context, or @apex-sentinel-staging pivot ... if this is wrong — I will re-check the cited code.
Useful? Reply @apex-sentinel-staging like, or @apex-sentinel-staging dislike <why> if it is not.
| /// A popover's dismiss region: a label or identifier that reads "dismiss popup", in any case, | ||
| /// with any surrounding whitespace. XCTest queries take it as a `MATCHES[c]` pattern. | ||
| public static let dismissPopupMarkerPattern = #"\s*dismiss popup\s*"# | ||
|
|
There was a problem hiding this comment.
🔵 Nit · AlertSurface's type strings are duplicated bare literals instead of sharing one set with actionableTypes
AlertSurface.swift:53 names the actionable kinds as the strings Button, Cell, Link, MenuItem, CheckBox, Switch, and matches()/candidates() compare the same vocabulary with bare literals: "Alert" and "Sheet" at lines 100-103, "Window" at 71 and 107, plus alertSurfaceNode's "Alert"/"Sheet" in RunnerTests+AlertObservation.swift. One typo ("Sheet" vs "Sheet ", "MenuItem" vs "MenuItem") silently stops a prompt kind from matching, and matches(node.type) reads as an ad-hoc string comparison where the rest of the module uses typed cases. Expose the vocabulary as named constants or an AlertSurfaceNodeType enum so actionableTypes and matches draw from it.
Suggested change
Give the node-type vocabulary one owner (constants or an enum used by both actionableTypes and matches), and reuse it in the runner's alertSurfaceNode mapping.
Details
persona: maintainability
Reply @apex-sentinel-staging note ... to add context, or @apex-sentinel-staging pivot ... if this is wrong — I will re-check the cited code.
Useful? Reply @apex-sentinel-staging like, or @apex-sentinel-staging dislike <why> if it is not.
| }, | ||
| }); | ||
| const { udid, bundle, name } = values; | ||
| if (!udid || !bundle || !name || !/^[a-z0-9-]+$/.test(name)) { |
There was a problem hiding this comment.
🔵 Nit · The capture script's format error is reported as a usage error
scripts/capture-alert-surface.ts:18-21 puts the !/^[a-z0-9-]+$/.test(name) check in the same condition as the three missing flags, so --name iPhone_Duo prints "Usage: pnpm capture:alert-surface --udid ..." and gives no hint that the name format is what it rejected, while the README asks for <device>-<pose>-<app>-<prompt>. Split the name-format check out and name the constraint.
| if (!udid || !bundle || !name || !/^[a-z0-9-]+$/.test(name)) { | |
| if (!udid || !bundle || !name) { | |
| throw new Error( | |
| 'Usage: pnpm capture:alert-surface --udid <simulator> --bundle <bundle id> --name <kebab-case-name>', | |
| ); | |
| } | |
| if (!/^[a-z0-9-]+$/.test(name)) { | |
| throw new Error(`--name must be kebab-case ([a-z0-9-]+); got ${name}.`); | |
| } |
Details
persona: maintainability
Reply @apex-sentinel-staging note ... to add context, or @apex-sentinel-staging pivot ... if this is wrong — I will re-check the cited code.
Useful? Reply @apex-sentinel-staging like, or @apex-sentinel-staging dislike <why> if it is not.
| ); | ||
| } | ||
|
|
||
| const root = path.resolve(import.meta.dirname, '..'); |
There was a problem hiding this comment.
🔵 Nit · Capture build writes DerivedData into the repo's .tmp/ and never removes it
capture-alert-surface.ts builds the whole iOS runner into path.join(root, '.tmp', 'alert-surface-runner') (a full .xctestrun + app bundle tree, hundreds of MB) and removes only its os.tmpdir() scratch directory in the finally block. The repo has tmp-dir leak tooling (scripts/check-tmpdir-leaks.ts) and a clean-xcuitest-derived.mjs, and every other runner build funnels through $HOME/.agent-device/apple-runner/derived via resolve_default_derived_path in scripts/build-xcuitest-apple.sh, which that cleaner knows about. A per-command derived path under the checkout is invisible to that cleaner, so the first capture leaves an unreclaimed build tree inside the working tree. I did not confirm whether .tmp is git-ignored or whether the leak check covers it (the check and .gitignore were unread when the budget ended), so this is reported at low confidence.
Suggested change
Either reuse the shared $HOME/.agent-device/apple-runner/derived/alert-surface path that scripts/clean-xcuitest-derived.mjs reclaims, or remove the derived directory in the script's finally block.
Details
persona: javascript
Reply @apex-sentinel-staging note ... to add context, or @apex-sentinel-staging pivot ... if this is wrong — I will re-check the cited code.
Useful? Reply @apex-sentinel-staging like, or @apex-sentinel-staging dislike <why> if it is not.
| AGENT_DEVICE_XCUITEST_DESTINATION: 'generic/platform=iOS Simulator', | ||
| }, | ||
| }); | ||
| const products = path.join(derived, 'Build', 'Products'); |
There was a problem hiding this comment.
🔵 Nit · Capture script takes the first .xctestrun in the derived products directory
fs.readdirSync(products).find((file) => file.endsWith('.xctestrun')) picks whichever entry readdirSync happens to return first. The build is driven with AGENT_DEVICE_XCUITEST_ARCHS: 'arm64' and AGENT_DEVICE_XCUITEST_DESTINATION: 'generic/platform=iOS Simulator' into a fresh .tmp/alert-surface-runner, but the products directory is shared with anything else that wrote an .xctestrun there, and the order readdirSync returns is unspecified. If a second .xctestrun ever appears (a previous run under a different scheme/arch, or a reused directory after a partially failed build), the capture silently tests the wrong artifact and -only-testing:...testCaptureAlertSurfaceTree either fails confusingly or records a tree from a stale runner build. Sorting the matches, or requiring exactly one and naming the candidates on ambiguity, makes the failure legible.
Suggested change
Collect every .xctestrun in products, throw naming all of them when there is more than one, and pass the run's own scheme name as the selection filter.
Details
persona: javascript
Reply @apex-sentinel-staging note ... to add context, or @apex-sentinel-staging pivot ... if this is wrong — I will re-check the cited code.
Useful? Reply @apex-sentinel-staging like, or @apex-sentinel-staging dislike <why> if it is not.
|
The code looks good at 7b89cba, and the conflict from the earlier review no longer applies. Not blocking, and you can take or leave it: the recorded fixtures do not exercise the window-placement rule at AlertSurface.swift:71. I ran the candidates rule over all 5 recorded fixtures with and without the Window child viewport, and the results are identical. Only the hand-built landscape test at AlertSurfaceTests.swift:89 tells them apart, so either record a fixture where an alert's midpoint falls outside the application frame but inside its window, or note in the README that only that test covers the rule. No open thread of any priority still applies. These are already resolved: the TEST_RUNNER_ prefix thread (xcodebuild strips it before the test process reads the env; comment added) #4115 (comment); the child-viewport fallback thread (the rule from #4113 moved verbatim, unchanged here) #4115 (comment); the unfolded SpringBoard fixture thread (669x951 window under a 466x678 application matches native orientation and the unfolded Safari recording) #4115 (comment); and the three fixed at this commit: stdio inherit #4115 (comment), the preorder parentIndex check #4115 (comment), and the output directory cleanup #4115 (comment). CI is still running: 16 checks are in progress and none has failed. Smoke Tests and Repo Guards & Compatibility cover this change; the Mutants and Coverage jobs target packages this diff does not touch. I did not run swift test, the runner unit tests or the capture script, so pass counts are the author's. No test round-trips the runner encoder against FixtureRect, and the corpus has no infinite or non-finite frames, so those encode branches are checked only by reading. Before merge, the in-progress checks and the remaining review must finish green, and #4113, which this PR is stacked on, must merge first. |
Stacked on #4113.
Summary
A corpus of real accessibility trees, replayed on the host:
AlertSurfaceinAgentDeviceSnapshotPresentationdecides which node counts as each kind of prompt (alert, sheet, Safari dialog, dismiss popup), which window hosts it, and the presentation compared after a tap. The runner's post-tap check now calls it, and the runner's duplicate rule code is gone.apple/snapshot-presentation/Tests/AlertSurfaceCorpus/holds a recorded tree plus a reviewedexpect.swift testreplays every file in the required macOS lane.pnpm capture:alert-surface --udid --bundle --nameruns a runner test method on the simulator, with no wire or CLI change. Its README covers the workflow.Limit: the corpus covers paths that read snapshot trees. The SpringBoard alert search and taps read
XCUIElement.frame, which on a foldable is in a different coordinate space, so the corpus doesn't cover them.Validation
pnpm check:affected --run --head fea511f262: passed.swift test --package-path apple/snapshot-presentation: passed.🤖 Generated with Claude Code